<template>
  <div class="system-table-box marginT8">
    <div class="demo-image__preview f-ffs">
      <el-image
        v-if="url"
        :src="url"
        class="previewImage marginR16"
        :preview-src-list="srcList"
        fit="contain"
        preview-teleported
      />
      <el-upload
        v-model:file-list="fileList"
        class="avatar-uploader"
        :http-request="httpRequest"
        :headers="headers"
        list-type="picture-card"
        :show-file-list="false"
        name="fileData"
        accept=".jpg,.jpeg,.png,.gif"
        :on-preview="handlePreview"
        :on-progress="handleProgress"
        :on-success="handleSuccess"
        :on-error="handleError"
      >
        <el-icon class="avatar-uploader-icon">
          <icon-add-pic />
        </el-icon>
        <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 500kb
          </div>
        </template>
      </el-upload>
    </div>
    <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, defineProps, reactive, ref, watch } from "vue";

const baseURL = import.meta.env.VITE_BASE_URL;
import store from "@/store";
import { ElMessage, ElLoading } from "element-plus";
import service from "@/utils/system/request";
import md5 from "js-md5";
import { closeLoading, showLoading, showSuccessToast } from "@/utils/common";

const url = ref("");
const props = defineProps(["fileList", "imageFile"]);
const emit = defineEmits(["uploadImageFn"]);
const fileList = props.fileList;
const imageFile = props.imageFile;
url.value = props.imageFile;
console.log(props.imageFile, "imageFile");
const headers = ref({
  //携带token传递到后端
  Authorization: `Bearer ${store.state.user.token}`
});
const srcList = ref([]);
const loading = ref(null);
// loading =ref(null)
const loadProgress = ref(0); // 动态显示进度条
const progressFlag = ref(false); // 动态显示进度条
// : false, // 关闭进度条
const httpRequest = options => {
  showLoading("Uploading");
  let newfile = options.file;
  newfile = new File(
    [options.file],
    `${md5(newfile.name)}.${newfile.type.split("/").pop().toLowerCase()}`
  );
  newfile.uid = options.file.uid; // new File 没有uid属性，会导致组件底层报错，这里手动加上
  // console.log(newfile)
  const formData = new FormData(); //我是用FormData() 来 进行弄 上传文件的 二进制文件
  formData.append("fileData", newfile);
  service.post(`admin/upload/image`, formData).then(({ code, data }) => {
    closeLoading();
    if (code === 0) {
      showSuccessToast("上传成功");
      url.value = data;
      srcList.value.push(data);
      emit("uploadImageFn", data);
      console.log(data);
    }
  });
};
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePreview = file => {
  // console.log(file,'filefile')
};
const handleProgress = (event, file, fileList) => {
  // console.log(file, "filefile");
  progressFlag.value = true; // 显示进度条
  loadProgress.value = parseInt(event.percent); // 动态获取文件上传进度
  if (loadProgress.value >= 100) {
    loadProgress.value = 100;
    setTimeout(() => {
      progressFlag.value = false;
    }, 1000); // 一秒后关闭进度条
  }
};
watch(
  () => props.imageFile,
  newVal => {
    url.value = props.imageFile;
    srcList.value = [props.imageFile];
  },
  { deep: true }
);

// const loading = ElLoading.service({
//   lock: true,
//   text: 'Loading',
//   background: 'rgba(0, 0, 0, 0.7)',
// })
// setTimeout(() => {
//   loading.close()
// }, 2000)
// watch(
//   () => props.imageFile,
//   (newValue, oldValue) => {
//     debugger
//     console.log(newValue,'12222222')
//   },
//   { deep: true }
// );
const handleSuccess = response => {
  // loading.value.close()
  console.log(response, "上传成功");
  ElMessage({
    showClose: true,
    message: "上传成功",
    type: "success"
  });
  url.value = response.data;
  srcList.value.push(response.data);
  emit("uploadImageFn", response.data);
};
const handleError = file => {
  console.log(file);
};
</script>

<style lang="scss" scoped>
:deep(.avatar-uploader .avatar) {
  width: 120px;
  height: 100px;
  display: inline-block;
}

:deep(.el-upload__tip) {
  margin: 0;
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  width: 120px;
  height: 120px;
  text-align: center;
  position: absolute;
  left: 0;
  line-height: 120px;
}

:deep(.avatar-uploader .el-upload) {
  border: 2px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 120px;
  height: 120px;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
  color: #7e9cff !important;

  .avatar-uploader-icon {
    color: #7e9cff !important;
  }
}

.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  background: red;
}

.previewImage {
  min-width: 120px;
  max-width: 220px;
  height: 120px;
  border-radius: 6px;
}
</style>
